<?php

namespace app\api\library;

use Exception;
use think\exception\Handle;

/**
 * 自定义API模块的错误显示
 */
class ExceptionHandle extends Handle
{
    //隐藏敏感信息
    private function hidePath($data){
        if(is_array($data)){
            foreach ($data as $key => &$value) {
                if(is_string($value)){
                    $value = str_replace(ROOT_PATH, '', $value);
                }
                if(is_array($value)){
                    $value = $this->hidePath($value);
                }
            }
            return $data;
        }
        return str_replace(ROOT_PATH, '', $data);
    }
    public function render(Exception $e)
    {
        $data=[];
        $statuscode = $code = 500;
        $msg = $e->getMessage();
        // 在开发环境下返回详细信息
        if (\think\Config::get('app_debug')) {
            $msg = $e->getMessage();
            $data['file']=$this->hidePath($e->getFile());
            $data['line']=$e->getLine();
            $data['trace']=$this->hidePath($e->getTrace());
        }
        // 验证异常
        if ($e instanceof \think\exception\ValidateException) {
            $code = 0;
            $statuscode = 200;
            $msg = $e->getError();
        }
        // Http异常
        if ($e instanceof \think\exception\HttpException) {
            $statuscode = $code = $e->getStatusCode();
        }
        return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data], $statuscode);

        //其它此交由系统处理
        // return parent::render($e);
    }

}
